<template>
  <div class="clock-in-wrap">
    <div class="mar10t">
      <Checkbox v-model="isShowTimeRange"></Checkbox>
      筛选条件：
      <template v-if="isShowTimeRange">
        <DatePicker
          size="small"
          type="datetimerange"
          :value="datetimerange"
          @on-change="handleChangeDate('datetimerange', $event)"
        ></DatePicker>
      </template>
      <template v-else>
        <DatePicker
          transfer
          class="w150"
          size="small"
          type="date"
          :value="selectDate"
          @on-change="handleChangeDate('date', $event)"
        ></DatePicker>
        <span class="mar10l">时间：</span>
        <TimePicker
          transfer
          class="w100"
          size="small"
          type="time"
          :value="startTime"
          @on-change="handleChangeDate('startTime', $event)"
        ></TimePicker>
        <span class="mar10l">-</span>
        <TimePicker
          transfer
          class="w100"
          size="small"
          type="time"
          :value="endTime"
          @on-change="handleChangeDate('endTime', $event)"
        ></TimePicker>
      </template>
      <Button class="mar10l" type="primary" size="small" @click="doStatistics"
        >点击统计</Button
      >
    </div>
    <div class="mar10t">
      <Checkbox v-model="isSortNormal">成员默认排序</Checkbox>
      --
      <Checkbox v-model="isShowLeavePeople">显示离开人员</Checkbox>
    </div>
    <div class="mar10t">
      <table class="table">
        <tr>
          <th>序号</th>
          <th>QQ</th>
          <th>昵称</th>
          <th>
            提交时间
            <TableSort
              :order="getSortOrder('time')"
              @changeSort="changeSort('time', $event)"
            ></TableSort>
          </th>
          <th>
            状态
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyStatus">复制状态到剪贴板</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th>操作</th>
        </tr>
        <tr
          v-for="(item, index) in showList"
          :key="'search_result_' + index"
          :class="{ red: !item.time }"
        >
          <td class="center">{{ index + 1 }}</td>
          <td>{{ item.qq }}</td>
          <td>{{ item.nickname }}</td>
          <td class="center">
            {{ item.time || "-" }}
          </td>
          <td class="center">
            {{ item.time ? "是" : "-" }}
          </td>
          <td class="center">
            <a class="" @click="startSetTime(index)">设置时间</a>
            <Tooltip transfer content="复制到剪贴板,用于在补丁文件中">
              <a class="mar10l" @click="copy2qqHistory(item)">复制</a>
            </Tooltip>
          </td>
        </tr>
      </table>
    </div>
    <div v-if="isShowSetTime">
      <Modal footer-hide title="设置时间" v-model="isShowSetTime">
        <Form :label-width="100">
          <FormItem label="设置的成员">
            {{ setObj.nickname }}({{ setObj.qq }})
          </FormItem>
          <FormItem label="日期">
            <DatePicker
              :value="setObj.date"
              @on-change="handleChangeModalDate('setModalDate', $event)"
            ></DatePicker>
          </FormItem>
          <FormItem label="提交时间">
            <TimePicker
              :value="setObj.time"
              @on-change="handleChangeModalDate('setModalTime', $event)"
            ></TimePicker>
          </FormItem>
          <FormItem>
            <Button @click="doSetTime">点击设置</Button>
          </FormItem>
        </Form>
      </Modal>
    </div>
  </div>
</template>

<script>
import { cloneObj, splitPerson, copy2Clipboard } from "js/utils.js";
let nickNameObj = null;
const dayjs = require("dayjs");
export default {
  data() {
    return {
      selectDate: "",
      startTime: "",
      endTime: "",
      datetimerange: ["", ""],
      isShowTimeRange: false, // 是否选择区间
      searchList: [],
      sortKey: "time", // 排序key
      sortOrder: "asc", // 排序order
      isSortNormal: false, // 成员默认排序
      isShowLeavePeople: false, // 显示离开人员
      isShowSetTime: false,
      setObj: {
        index: -1,
        nickname: "",
        qq: "",
        date: "",
        time: "",
      },
    };
  },
  computed: {
    showList() {
      let list = cloneObj(this.searchList);
      if (!this.isShowLeavePeople) {
        list = list.filter((item) => !item.isLeave);
      }
      if (this.sortKey === "time") {
        list.sort((a, b) => {
          if (a.time && b.time) {
            if (this.sortOrder === "asc") {
              return dayjs(a.time).isAfter(b.time) ? 1 : -1;
            }
            return dayjs(a.time).isBefore(b.time) ? 1 : -1;
          }
          if (!a.time && !b.time) {
            return a.no > b.no ? 1 : -1;
          }
          if (!a.time) {
            return 1;
          }
          return -1;
        });
      } else if (this.sortKey === "no") {
        list.sort((a, b) => (a.no > b.no ? 1 : -1));
      }
      if (this.isSortNormal) {
        list = list.sort((a, b) => (a.no > b.no ? 1 : -1));
      }
      return list;
    },
  },
  watch: {
    isSortNormal(newval) {
      if (newval) {
        this.sortKey = "no";
      } else {
        this.sortKey = "time";
        this.sortOrder = "asc";
      }
    },
  },
  methods: {
    initData() {
      let now = dayjs();
      this.selectDate = now.format("YYYY-MM-DD");
      this.startTime = "06:40:00";
      this.endTime = "10:00:00";

      let date = dayjs(this.selectDate);
      this.datetimerange[0] = date.add("hour", 7).format("YYYY-MM-DD HH:mm:ss");
      this.datetimerange[1] = date
        .add("hour", 10)
        .format("YYYY-MM-DD HH:mm:ss");
    },
    handleChangeDate(tag, date) {
      if (this.isShowTimeRange) {
        this.datetimerange[0] = dayjs(date[0]).format("YYYY-MM-DD HH:mm:ss");
        this.datetimerange[1] = dayjs(date[1]).format("YYYY-MM-DD HH:mm:ss");
      } else {
        if (tag === "date") {
          this.selectDate = dayjs(date).format("YYYY-MM-DD");
        } else if (tag === "startTime") {
          this.startTime = date;
        } else if (tag === "endTime") {
          this.endTime = date;
        }
      }
    },
    handleChangeModalDate(tag, date) {
      if (tag === "setModalDate") {
        this.setObj.date = dayjs(date).format("YYYY-MM-DD");
      } else if (tag === "setModalTime") {
        this.setObj.time = date;
      }
    },
    async doStatistics() {
      let members = this.$store.getters.getMembers();
      if (members.length === 0) {
        this.$global.log("请先导入成员");
        return;
      }
      let text = await this.$global.getFileText("small");
      if (!text) {
        this.$global.log("请选择小群文件");
        return;
      }
      let qqObj = {};
      nickNameObj = {};
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        qqObj[item.qq] = item;
        nickNameObj[item.nickname] = item;
      }
      let startTime = "";
      let endTime = "";
      if (this.isShowTimeRange) {
        startTime = this.datetimerange[0];
        endTime = this.datetimerange[1];
      } else {
        startTime = this.selectDate + " " + this.startTime;
        endTime = this.selectDate + " " + this.endTime;
      }
      let allList = splitPerson(text);
      let obj = {};
      for (let i = 0, n = allList.length; i < n; i++) {
        let item = allList[i];
        if (item.qq) {
          if (!qqObj[item.qq]) {
            continue;
          }
          if (item.nickname !== qqObj[item.qq].nickname) {
            item.nickname = qqObj[item.qq].nickname;
          }
        } else {
          if (!nickNameObj[item.nickname]) {
            continue;
          }
          item.qq = nickNameObj[item.nickname].qq;
        }
        if (item.time < startTime || item.time > endTime) {
          continue;
        }
        if (!obj[item.qq]) {
          obj[item.qq] = item;
        }
        if (obj[item.qq].time > item.time) {
          obj[item.qq] = item;
        }
      }
      let searchList = [];
      for (let key in obj) {
        let item = obj[key];
        searchList.push({
          qq: item.qq,
          nickname: item.nickname,
          isLeave: nickNameObj[item.nickname].isLeave,
          time: item.time || "",
          no: nickNameObj[item.nickname].no,
        });
      }
      let noResult = members.filter((item) => !obj[item.qq]);
      for (let i = 0, n = noResult.length; i < n; i++) {
        let item = noResult[i];
        searchList.push({
          qq: item.qq,
          nickname: item.nickname,
          isLeave: item.isLeave,
          time: "",
          no: item.no,
        });
      }
      this.searchList = searchList;
      new this.$tableSelect(".clock-in-wrap .table");
    },
    // 更改排序
    changeSort(key, order) {
      this.sortKey = key;
      this.sortOrder = order;
    },
    // 获取排序order
    getSortOrder(key) {
      if (key === this.sortKey) {
        return this.sortOrder;
      }
      return "";
    },
    // 设置时间
    startSetTime(index) {
      let item = this.showList[index];
      this.setObj.index = index;
      this.setObj.nickname = item.nickname;
      this.setObj.qq = item.qq;
      if (item.time) {
        this.setObj.date = dayjs(item.time).format("YYYY-MM-DD");
        this.setObj.time = dayjs(item.time).format("HH:mm:ss");
      } else {
        this.setObj.date = this.selectDate;
        this.setObj.time = dayjs().format("HH:mm:ss");
      }
      this.isShowSetTime = true;
    },
    doSetTime() {
      if (!this.setObj.date) {
        this.$log("请选择日期");
        return;
      }
      if (!this.setObj.time) {
        this.$log("请选择时间");
        return;
      }
      let index = this.setObj.index;
      let item = this.showList[index];
      let index2 = -1;
      item.time = this.setObj.date + " " + this.setObj.time;
      for (let i = 0, n = this.searchList.length; i < n; i++) {
        let item2 = this.searchList[i];
        if (item2.qq === item.qq) {
          index2 = i;
          break;
        }
      }
      this.searchList[index2] = item;
      this.$set(this.searchList, index2, this.searchList[index2]);
      this.isShowSetTime = false;
    },
    // 复制为QQ记录格式
    copy2qqHistory(item) {
      if (!item.time) {
        this.$Message.error("请选择时间");
        return;
      }
      let str = `${item.time} ${item.nickname}(${item.qq})
`;
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    // 复制状态
    copyStatus() {
      let str = "";
      for (let i = 0, n = this.showList.length; i < n; i++) {
        let item = this.showList[i];
        let time = item.time;
        if (!time) {
          str += "-";
        } else if (item.isDelay) {
          str += `${time}（补）`;
        } else {
          str += "是";
        }
        str += "\n";
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
  },
  mounted() {
    this.initData();
  },
};
</script>

<style lang="less">
.clock-in-wrap {
}
</style>
